package com.example.time;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.*;

/*
 * LocalDate、LocalTime、LocalDateTime
 *  LocalDate、LocalTime、LocalDateTime类的实例时不可变的对象，分别表示使用ISO-8601日历系统的日期、时间、日期和时间。
 *  它们提供了简单的日期或时间，并不包含当前的时间信息。也不包含与时区相关的信息。
 */

//001
public class TestSimpleDateFormat {
    //SimpleDateFormat的线程安全问题
    @Test
    public void test1() throws ExecutionException, InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Callable<Date> call = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return sdf.parse("20200923");
            }
        };
        ArrayList<Future<Date>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Date> submit = pool.submit(call);
            futures.add(submit);
        }
        for (Future<Date> f : futures) {
            System.out.println(f.get());
        }
        pool.shutdown();
    }

    //SimpleDateFormat的线程安全问题传统解决方式
    @Test
    public void test2() throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Callable<Date> call = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return DateFormatThreadLocal.convert("20200923");
            }
        };
        ArrayList<Future<Date>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Date> submit = pool.submit(call);
            futures.add(submit);
        }
        for (Future<Date> f : futures) {
            System.out.println(f.get());
        }
        pool.shutdown();
    }

    //Java8新日期API
    @Test
    public void test3() throws ExecutionException, InterruptedException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        ExecutorService pool = Executors.newFixedThreadPool(10);
        Callable<LocalDate> call = new Callable<LocalDate>() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("20200923", formatter);
            }
        };
        ArrayList<Future<LocalDate>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<LocalDate> submit = pool.submit(call);
            futures.add(submit);
        }
        for (Future<LocalDate> f : futures) {
            System.out.println(f.get());
        }
        pool.shutdown();
    }
}
